package com.htfyun.fragment.library;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.htfyun.Constants;
import com.htfyun.fragment.base.BaseWithPageNumberAdapter;
import com.htfyun.fragment.library.child.LibraryBaseFragment;
import com.htfyun.utils.DebugLog;
import com.htfyun.utils.DisplayUtil;
import com.squareup.picasso.Picasso;

import org.geometerplus.android.fbreader.FBReader;
import org.geometerplus.android.fbreader.covers.CoverManager;
import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
import org.geometerplus.android.fbreader.util.AndroidImageSynchronizer;
import org.geometerplus.fbreader.Paths;
import org.geometerplus.fbreader.book.Book;
import org.geometerplus.fbreader.book.BookEvent;
import org.geometerplus.fbreader.book.IBookCollection;
import org.geometerplus.fbreader.formats.PluginCollection;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.filetypes.FileType;
import org.geometerplus.zlibrary.core.filetypes.FileTypeCollection;
import org.geometerplus.zlibrary.core.util.RationalNumber;
import org.geometerplus.zlibrary.ui.android.R;

import java.io.File;
import java.util.List;

/**
 * Created by sst on 2017/12/27.
 */

public class LibraryBookRecyclerViewAdapter extends BaseWithPageNumberAdapter<File, LibraryBookRecyclerViewAdapter.MyViewHolder> {

    private CoverManager myCoverManager;
    public AndroidImageSynchronizer ImageSynchronizer;

    private final BookCollectionShadow myCollection = new BookCollectionShadow();


    public LibraryBookRecyclerViewAdapter(Activity context) {

        super(context);
        
        if (myCoverManager == null ) {
            ImageSynchronizer = new AndroidImageSynchronizer(context);

            final int coverHeight = DisplayUtil.dipToPix(getContext(), Constants.COVER_HEIGHT);//view.getMeasuredHeight();
            final int coverWidth = DisplayUtil.dipToPix(getContext(), Constants.COVER_WIDTH);//view.getMeasuredHeight();
            myCoverManager = new CoverManager(context, ImageSynchronizer, coverWidth, coverHeight);

            myCollection.bindToService(getContext(), new Runnable() {
                public void run() {

                    myCollection.addListener(bookListener);
                    notifyDataSetChanged();

                }
            });
        }
    }
   
    @Override
    public MyViewHolder getViewHolder(View view) {
        return new MyViewHolder(view);
    }

    @Override
    public int getLayoutId() {
        return R.layout.htfyun_library_tree_item;
    }

    @Override
    public void onItemClick(int position, File file) {
        Book book = myCollection.getBookByFile(file.getPath());
        if (book != null) {
            FBReader.openBookActivity(getContext(), book, null);
        }
    }


    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        super.onBindViewHolder(holder, position);
        
        List<File> items = getItems();
        if (items.size() <= position) {
            return;
        }

        File file = items.get(position);

        Book book = myCollection.getBookByFile(file.getPath());
        if (book != null) {
            holder.itemName.setText(book.getTitle());

            holder.itemAuthor.setText(book.authorsName());

            holder.progressBarPagePercent.setMax(100);
            holder.progressBarPagePercent.setProgress(0);

            RationalNumber rationalNumber = book.getProgress();

            if (rationalNumber != null) {

                holder.progressBarPagePercent.setMax((int) book.getProgress().Denominator);
                holder.progressBarPagePercent.setProgress((int) book.getProgress().Numerator);
            }

            final ImageView coverView = holder.itemIcon;
            if (!myCoverManager.trySetCoverImage(coverView, book, PluginCollection.Instance(Paths.systemInfo(getContext())))) {

                coverView.setImageResource(getCoverResourceId(book));
            }
        }

    }

    public void onDestroy() {
        myCollection.unbind();
        
        if (ImageSynchronizer != null) {
            ImageSynchronizer.clear();
            ImageSynchronizer = null;
        }

        if (myCoverManager != null) {
            myCoverManager = null;
        }
        
    }

    private int getCoverResourceId(Book book) {
        if (book != null) {

            final FileType fileType = FileTypeCollection.Instance.typeForFile(ZLFile.createFileByPath(book.getPath()));
            DebugLog.e("fileTyp.id = " + fileType.Id);
            if (fileType.Id.equalsIgnoreCase("TXT")) {
                return (R.drawable.ic_shelf_txt);
            } else if (fileType.Id.equalsIgnoreCase("EPUB")) {
                return (R.drawable.ic_shelf_epub);
            }

        }

        return (R.drawable.ic_shelf_txt);

    }
    
    

    private IBookCollection.Listener<Book> bookListener = new IBookCollection.Listener<Book>() {
        @Override
        public void onBookEvent(BookEvent event, Book book) {
            
        }

        @Override
        public void onBuildEvent(IBookCollection.Status status) {

        }
    };
    

    class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView itemIcon;
        TextView itemName;
        TextView itemAuthor;
        ProgressBar progressBarPagePercent;

        public MyViewHolder(View itemView) {
            super(itemView);
            itemIcon = (ImageView)itemView.findViewById(R.id.library_tree_item_icon);
            itemName = (TextView) itemView.findViewById(R.id.library_tree_item_name);
            itemAuthor = (TextView) itemView.findViewById(R.id.library_tree_item_author);
            progressBarPagePercent = (ProgressBar) itemView.findViewById(R.id.progressBarPagePercent);
        }
    }

}
